package com.lz.sports.ui

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lz.comm.BR
import com.lz.comm.SP
import com.lz.helper.idcard.IDCardHelper
import com.lz.helper.idcard.IDCardInfo
import com.lz.library.adapter.BaseAdapter
import com.lz.library.base.BaseActivity
import com.lz.library.extension.APP
import com.lz.library.extension.click
import com.lz.library.extension.resString
import com.lz.library.extension.showToast
import com.lz.sports.R
import com.lz.sports.adapter.InspectAdapter
import com.lz.sports.bean.CommonModel
import com.lz.sports.bean.ParcelableString
import com.lz.sports.core.K_RULE_EXAM_GROUP_COUNT
import com.lz.sports.core.ProjectManager
import com.lz.sports.core.SoundHelper
import com.lz.sports.core.v_ruleExamGroupCount
import com.lz.sports.databinding.ActInspectBinding
import com.lz.sports.ui.checkmodel.FingerDialog
import com.lz.sports.dialog.ParcelableSelectDialog
import com.lz.sports.dialog.WarningDialog
import com.lz.sports.ui.checkmodel.FaceIdentifyDialog
import com.lz.sports.ui.checkmodel.FeatureResult
import com.lz.sports.utils.ToastUtils
import com.lz.sports.vm.InspectViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

//检录
class InspectActivity : BaseActivity<InspectViewModel, ActInspectBinding>(),
    IDCardHelper.IDCardCallback,
    FingerDialog.OnResultListener,
    WarningDialog.OnWarningConfirmListener,
    ParcelableSelectDialog.OnSelectedListener{

    companion object {
        //模式弹窗
        private const val REQUEST_MODEL = 1

        //组选择
        private const val REQUEST_GROUP = 2

        //清空
        private const val REQUEST_CLEAR = 1

        //取消
        private const val REQUEST_CANCEL = 2
    }

    private val adapter by lazy {
        val size = SP.getInt(K_RULE_EXAM_GROUP_COUNT, v_ruleExamGroupCount)
        InspectAdapter.newInspectAdapter(size)
    }

    //身份证扫描
    private val idCardHelper by lazy { IDCardHelper(APP, true, this) }

    private val soundHelper by lazy { SoundHelper() }

    private var faceDialog: FaceIdentifyDialog? = null

    override fun getLayoutRes(): Int = R.layout.act_inspect

    override fun getVMVariableId(): Int = BR.vm

    override fun initObserve() {
        viewModel.currentExamInspect.observe(this) {
            if (adapter.hasExamInspect(it)) {
                ToastUtils.showMyToast(R.string.inspect_over, Toast.LENGTH_SHORT)
            } else {
                adapter.addExamInspect(it)
                if (viewModel.modelPosition == 0) {
                    adapter.next()
                }
            }
        }
        viewModel.examineeAndCardInfo.observe(this) {
            if (adapter.hasExaminee(it.examinee)) {
                ToastUtils.showMyToast(R.string.inspect_over, Toast.LENGTH_SHORT)
            } else {
                faceDialog = FaceIdentifyDialog.show(this@InspectActivity, it.examinee,
                    it.idCardInfo, viewModel.inspectType, ProjectManager.personThreshold(), ProjectManager.faceThreshold())
            }
        }

        viewModel.saveOver.observe(this) {
            adapter.clear()
        }

        LiveEventBus.get("FaceIdentifyDialog", FeatureResult::class.java).observe(this) { featureResult ->
            if (adapter.hasExaminee(featureResult.examinee)) {
                ToastUtils.showMyToast(R.string.inspect_over, Toast.LENGTH_SHORT)
            } else {
                viewModel.addExamInspect(featureResult)
            }
        }
    }

    override fun initData(savedState: Bundle?) {
        soundHelper.init(intArrayOf(com.lz.helper.R.raw.idcard_read, com.lz.helper.R.raw.idcard_success))
        binding.rvList.adapter = adapter
        adapter.setOnItemClickListener(object : BaseAdapter.OnItemClickListener {
            override fun onItemClick(view: View, position: Int) {
                if (viewModel.modelPosition > 0) { //手动模式
                    adapter.clickItem(position)
                }
            }
        })

        lifecycleScope.launch {
            arrayOf(binding.tvModel, binding.tvGroup, binding.tvClear, binding.tvCancel, binding.tvSave).click()
                .collect {
                    when (it.id) {
                        R.id.tv_model -> ParcelableSelectDialog.show(
                            this@InspectActivity, R.string.select.resString(),
                            viewModel.currentModel.value, viewModel.models, REQUEST_MODEL
                        )
                        R.id.tv_group -> {
                            if (viewModel.groupList == null || viewModel.groupList!!.isEmpty()) {
                                R.string.group_un.showToast()
                            } else {
                                ParcelableSelectDialog.show(
                                    this@InspectActivity,
                                    R.string.select.resString(),
                                    viewModel.currentGroup.value,
                                    viewModel.groupList as ArrayList<out ParcelableString>, REQUEST_GROUP
                                )
                            }
                        }
                        R.id.tv_clear -> {
                            if (adapter.hasInspected()) {
                                WarningDialog.show(
                                    this@InspectActivity,
                                    R.string.inspect_cancel.resString(),
                                    requestCode = REQUEST_CLEAR
                                )
                            } else {
                                adapter.clear()
                            }
                        }
                        R.id.tv_cancel -> {
                            if (adapter.hasInspected()) {
                                WarningDialog.show(
                                    this@InspectActivity,
                                    R.string.inspect_cancel.resString(),
                                    requestCode = REQUEST_CANCEL
                                )
                            } else {
                                finish()
                            }
                        }
                        R.id.tv_save -> {
                            val list = adapter.inspectExamineeList()
                            if (list.isNotEmpty()) {
                                viewModel.save(list)
                            }
                        }
                    }
                }
        }

        idCardHelper.start()
    }

    override fun onCardResult(idCardInfo: IDCardInfo) {
        lifecycleScope.launch {
            soundHelper.play(1)
        }
        when(viewModel.inspectType) {
            CommonModel.ID_CARD_EXAM, CommonModel.ID_CARD_ID, CommonModel.ID_CARD_FACE_EXAM, CommonModel.ID_CARD_AND -> {
                if (faceDialog?.dialog?.isShowing == true) return
                viewModel.examineeFace(idCardInfo)
            }
            else -> viewModel.examineeIdCard(idCardInfo)
        }
    }

    override fun onResume() {
        super.onResume()
        idCardHelper.restart()
        lifecycleScope.launch {
            delay(500)
            soundHelper.play(0)
        }
    }

    override fun onPause() {
        super.onPause()
        idCardHelper.pause()
    }

    override fun onDestroy() {
        super.onDestroy()
        idCardHelper.quit()
        soundHelper.release()
    }

    override fun onCardError(err: Int) {
    }

    override fun onResult(threshold: Int) {
    }

    override fun onConfirm(dialog: WarningDialog, requestCode: Int) {
        dialog.dismiss()
        when (requestCode) {
            REQUEST_CANCEL -> finish()
            REQUEST_CLEAR -> adapter.clear()
        }
    }

    override fun onSelected(dialog: ParcelableSelectDialog, position: Int, requestCode: Int) {
        dialog.dismiss()
        when (requestCode) {
            REQUEST_MODEL -> {
                if (viewModel.selectModel(position) && position == 0) {
                    adapter.next()
                }
            }
            REQUEST_GROUP -> viewModel.selectGroup(position)
        }
    }
}